const express = require("express")
const router = express.Router()
const Marker = require("../models/marker")

// 格式化标记点位置数据
const formatPosition = (position) => {
  if (typeof position === "string") {
    const pos = JSON.parse(position)
    return {
      longitude: Number(pos.longitude),
      latitude: Number(pos.latitude),
      height: Number(pos.height || 0),
    }
  }
  return position
}

// 获取所有标记点
router.get("/getMarkers", async (req, res) => {
  try {
    const markers = await Marker.findAll({
      order: [["created_at", "DESC"]],
    })
    const formattedMarkers = markers.map((marker) => ({
      ...marker.toJSON(),
      position: formatPosition(marker.position),
    }))
    res.json({
      code: 200,
      data: formattedMarkers,
      message: "获取标记点列表成功",
    })
  } catch (error) {
    res.json({ code: 500, message: "获取标记点列表失败" })
  }
})

// 添加标记点
router.post("/addMarker", async (req, res) => {
  try {
    const { position, type, color } = req.body
    const positionJson =
      typeof position === "string"
        ? position
        : JSON.stringify({
            longitude: Number(position.longitude),
            latitude: Number(position.latitude),
            height: Number(position.height || 0),
          })
    const marker = await Marker.create({
      ...req.body,
      position: positionJson,
      type: type || "default",
      color: color || "#ff4d4f",
    })
    res.json({
      code: 200,
      data: { ...marker.toJSON(), position: formatPosition(marker.position) },
      message: "添加标记点成功",
    })
  } catch (error) {
    res.json({ code: 500, message: "添加标记点失败" })
  }
})

// 更新标记点
router.put("/updateMarker/:id", async (req, res) => {
  try {
    const marker = await Marker.findByPk(req.params.id)
    if (!marker) return res.json({ code: 404, message: "标记点不存在" })
    await marker.update({
      ...req.body,
      color: req.body.color || "#ff4d4f",
    })
    res.json({
      code: 200,
      data: { ...marker.toJSON(), position: formatPosition(marker.position) },
      message: "更新标记点成功",
    })
  } catch (error) {
    res.json({ code: 500, message: "更新标记点失败" })
  }
})

// 删除标记点
router.delete("/deleteMarker/:id", async (req, res) => {
  try {
    const marker = await Marker.findByPk(req.params.id)
    if (!marker) return res.json({ code: 404, message: "标记点不存在" })
    await marker.destroy()
    res.json({ code: 200, message: "删除标记点成功" })
  } catch (error) {
    res.json({ code: 500, message: "删除标记点失败" })
  }
})

module.exports = router
